<template>
  <el-form
    :model="infoForm"
    :rules="infoRules"
    label-position="right"
    label-width="80px"
    ref="formRef"
  >
    <el-form-item>
      <el-upload
        :action="uploadUrl"
        class="w-full text-center"
        :before-upload="beforeAvatarUpload"
        :on-success="handleAvatarSuccess"
        :on-error="handleAvatarError"
        :show-file-list="false"
        :data="uploadData"
      >
        <div>
          <div class="avatar-box inline-block cursor-pointer relative overflow-hidden">
            <img class="h-24 w-24 inline-block" :src="currentAvatar" alt="" />
            <div class="box-mask absolute inset-0">
              <img
                src="../../../assets/images/camera.svg"
                alt=""
                class="absolute camera-icon left-2/4 top-2/4"
              />
              <div class="text-white w-full -translate-x-1/2 left-2/4 top-2/4 absolute">
                修改专栏封面
              </div>
            </div>
          </div>
        </div>
      </el-upload>
    </el-form-item>
    <el-form-item label="专栏名称" prop="title">
      <el-input v-model="infoForm.title" placeholder="请输入专栏名称" maxlength="8" />
    </el-form-item>
    <el-form-item label="专栏简介">
      <el-input
        type="textarea"
        :rows="4"
        v-model="infoForm.description"
        placeholder="请输入简介内容..."
        resize="none"
      />
    </el-form-item>
  </el-form>
  <div class="text-right">
    <el-button type="primary" @click="saveInfo" :loading="loading">保存</el-button>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, onMounted } from 'vue'
import { useUserStore } from '@/store/user'
import {
  ElMessage,
  ElForm,
  ElFormItem,
  FormRules,
  ElInput,
  ElButton,
  ElUpload,
  UploadProps,
  FormInstance,
} from 'element-plus'
import { RequestError, RequestDto } from '@/services/ApiServer/request'
import { UploadDto } from '@/services/ApiServer/CommonRequest'
import { updateUserInfo } from '@/services/ApiServer/signInRequest'
import { getColumnDetail, updateColumnData } from '@/services/ApiServer/ColumnsRequest'

export default defineComponent({
  name: 'personalInfo',
  components: {
    ElForm,
    ElFormItem,
    ElInput,
    ElButton,
    ElUpload,
  },
  setup() {
    let loading = ref(false)
    const userStore = useUserStore()
    let infoForm = reactive({
      title: '',
      description: '',
      avatar: '',
    })
    const infoRules: FormRules = {
      title: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
    }
    const currentAvatar = ref(new URL('../../../assets/images/avatar.svg', import.meta.url).href)
    const getColumnInfo = async () => {
      if (!userStore.userInfo?.column) return
      const res = await getColumnDetail(userStore.userInfo?.column)
      if (res && res.code === 0 && res.data) {
        infoForm.title = res.data.title
        infoForm.description = res.data.description
        if (res.data.avatar) {
          infoForm.avatar = res.data.avatar._id
          currentAvatar.value = res.data.avatar.url
        }
      }
    }
    const uploadUrl = `${import.meta.env.VITE_APP_SERVER}upload`
    const uploadData = {
      icode: import.meta.env.VITE_APP_ICODE,
    }
    // 上传前校验
    const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
      if (rawFile.size / 1024 > 500) {
        ElMessage.warning('上传图片不能超过500KB！')
        return false
      }
      if (!/^image\/(jpeg|png|jpg)$/.test(rawFile.type)) {
        ElMessage.warning('请上传JPG/PNG格式图片！')
        return false
      }
      return true
    }
    // 上传成功钩子
    const handleAvatarSuccess: UploadProps['onSuccess'] = (
      response: RequestDto<UploadDto>,
      uploadFile
    ) => {
      if (response.code === 0 && uploadFile.raw) {
        currentAvatar.value = URL.createObjectURL(uploadFile.raw)
        infoForm.avatar = response.data._id
      }
    }
    // 上传失败钩子
    const handleAvatarError: UploadProps['onError'] = (error) => {
      const response: RequestError = JSON.parse(error.message)
      ElMessage.error(response.error)
    }
    const formRef = ref<FormInstance | null>()
    // 保存
    const saveInfo = () => {
      formRef.value?.validate(async (valid) => {
        if (valid && userStore.userInfo?.column) {
          loading.value = true
          const res = await updateColumnData(userStore.userInfo.column, infoForm)
          if (res && res.code === 0) {
            ElMessage.success('修改成功！')
          }
          loading.value = false
        }
      })
    }
    onMounted(() => {
      getColumnInfo()
    })
    return {
      infoForm,
      infoRules,
      currentAvatar,
      uploadUrl,
      uploadData,
      loading,
      formRef,
      beforeAvatarUpload,
      handleAvatarSuccess,
      handleAvatarError,
      saveInfo,
    }
  },
})
</script>

<style lang="scss" scoped>
.avatar-box {
  border: 1px solid #dcdfe6;
  padding: 20px;
  border-radius: 50%;
  .box-mask {
    background-color: #121212;
    opacity: 0.7;
    .camera-icon {
      margin-top: -36px;
      margin-left: -18px;
    }
  }
}
</style>
